<template>
  <el-dialog
    width="800"
    :title="props.dialogTitle"
    v-model="visible"
    draggable
    class="dialog"
    @close="closeDialog"
  >
    <el-form
      :model="formParams"
      :disabled="_disabled"
      :rules="rules"
      ref="formRef"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          :disabled="selectDisabled"
          v-model="formParams.cityName"
          @change="handleChangeCity"
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择礼包" prop="couponPackId">
        <el-button :disabled="selectDisabled" link type="primary" @click="handleSelect()">{{
          giftBagData.packName || '选择优惠券礼包'
        }}</el-button>
      </el-form-item>
      <el-form-item label="售卖价格" prop="price">
        <el-input-number
          v-model="formParams.price"
          :min="0.01"
          :max="9999.99"
          :precision="2"
          controls-position="right"
        />
        元
      </el-form-item>
      <el-form-item label="售卖库存数量" prop="packNum">
        <!-- :max="giftBagData.surplusCount ?? maxPackNum" -->
        <el-input-number
          v-model="formParams.packNum"
          :min="minPackNum"
          :max="maxPackNum"
          controls-position="right"
        />
        份
      </el-form-item>
      <el-form-item label="小程序礼包排序" prop="sort">
        <el-input-number v-model="formParams.sort" :min="1" :max="10" controls-position="right" />
      </el-form-item>
      <el-form-item label="优惠券礼包购买说明" prop="declare">
        <el-input
          v-model="formParams.declare"
          style="width: 240px"
          maxlength="200"
          :rows="4"
          type="textarea"
          placeholder="请输入购买说明，最多200字"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tagId">
        <el-select v-model="formParams.tagId" placeholder="请选择" clearable>
          <el-option
            v-for="item in tagComboList"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品缩略图" prop="shopImg">
        <ImageUploadByType
          v-model="formParams.shopImg"
          :isShowTip="false"
          uploadType="1"
          :limit="1"
          :fileSize="2"
          :validateAspectRatio3To2="true"
        />
        <div>图片比例为600px*400px，请上传 大小不超过 2MB 格式为 png/jpg/jpeg 的文件</div>
      </el-form-item>
    </el-form>
    <div class="confirmedBox" v-show="props.dialogTitle !== '详情'">
      <el-button @click="confirmed()">确认</el-button>
      <el-button @click="visible = false">取消</el-button>
    </div>
  </el-dialog>
  <listDialog ref="listRef" @passingValue="passingValue" />
</template>
<script setup>
import {
  addGiftPackSalesApi,
  editGiftPackSalesApi,
  getGiftPackSalesDetailsApi,
  getGiftPackSortApi
} from '@/api/marketing/virtualGiftPack'
import listDialog from './list'
import { formatTexarea } from '@/utils/tools'
import useGlobalStore from '@/store/modules/global'
import { getTagComboList } from '@/api/meal/comboTag'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)

const props = defineProps({
  dialogTitle: {
    type: String,
    default: ''
  }
})
const listRef = ref(null)
const visible = ref(false)
const tagComboList = ref([])
const formParams = ref({
  couponPackId: null,
  price: null,
  packNum: null,
  sort: null,
  declare: null,
  tagId: null,
  shopImg: null,
  packSurplusCount: 0,
  soldQuantity: 0,
  currentStock: 0,
  status: null,
  cityName: ''
})
const formRef = ref(null)
const _disabled = computed(() => props.dialogTitle === '详情')
const selectDisabled = computed(() => props.dialogTitle === '编辑')
const minPackNum = ref(0)

const maxPackNum = ref(0)

const rules = {
  cityName: [{ required: true, message: '请选择', trigger: 'change' }],
  couponPackId: [{ required: true, message: '请选择礼包', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  packNum: [{ required: true, message: '请输入售卖库存数量', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  declare: [{ required: true, message: '请输入说明', trigger: 'blur' }],
  tagId: [{ required: true, message: '请选择标签', trigger: 'change' }],
  shopImg: [{ required: true, message: '请上传图片', trigger: 'blur' }]
}
function init(row) {
  visible.value = true
  formParams.value.cityName = row.cityName
  getTagCombo()
  getData({ ...row })
}

function getTagCombo() {
  getTagComboList({
    pageNum: 1,
    pageSize: 9999,
    enable: 1,
    cityName: formParams.value.cityName
  }).then((res) => {
    console.log(res)
    tagComboList.value = res.rows || []
  })
}

// 切换城市
function handleChangeCity() {
  // formParams.value.couponPackId = null
  // getGiftPackSortApi({ cityName: formParams.value.cityName })
  //   .then((res) => {
  //     formParams.value.sort = res.data
  //   })
  //   .catch((err) => {
  //     console.error('获取礼包排序失败', err)
  //   })
  minPackNum.value = 0
  maxPackNum.value = 0
  const cityName = formParams.value.cityName
  closeDialog()
  init({ cityName })
}

/**获取数据 */
function getData(row) {
  console.log(props.dialogTitle)
  if (props.dialogTitle !== '新增') {
    getGiftPackSalesDetailsApi(row.id)
      .then((res) => {
        console.log(res)
        giftBagData.value.packName = res.data.packName
        formParams.value = {
          ...res.data,
          declare: formatTexarea(res.data.declare, true)
        }
        if (props.dialogTitle === '编辑') {
          if (formParams.value.status === 0) {
            minPackNum.value = formParams.value.soldQuantity
          } else if (formParams.value.status === 2) {
            minPackNum.value = formParams.value.soldQuantity + 1
          }
          handleMaxMin()
        } else if (props.dialogTitle === '详情') {
          minPackNum.value = formParams.value.soldQuantity
          maxPackNum.value =
            formParams.value.packSurplusCount +
            formParams.value.soldQuantity +
            formParams.value.currentStock
        }
        console.log('minPackNum.value', minPackNum.value)
        console.log('maxPackNum.value', maxPackNum.value)
      })
      .catch((err) => {
        console.error('获取礼包销售详情失败', err)
      })
  } else {
    getGiftPackSortApi({ cityName: formParams.value.cityName })
      .then((res) => {
        formParams.value.sort = res.data
      })
      .catch((err) => {
        console.error('获取礼包排序失败', err)
      })
  }
}
/**处理最大值以及最小值 */
function handleMaxMin() {
  if (
    formParams.value.soldQuantity + 1 >
    formParams.value.packSurplusCount +
      formParams.value.soldQuantity +
      formParams.value.currentStock
  ) {
    maxPackNum.value =
      formParams.value.packSurplusCount +
      formParams.value.soldQuantity +
      formParams.value.currentStock +
      1
  } else {
    maxPackNum.value =
      formParams.value.packSurplusCount +
      formParams.value.soldQuantity +
      formParams.value.currentStock
  }
}
function confirmed() {
  formRef.value.validate((valid) => {
    if (valid) {
      formParams.value.shopImg = formParams.value.shopImg[0].url ?? formParams.value.shopImg
      if (props.dialogTitle === '新增') {
        const params = {
          ...formParams.value,
          soldQuantity: 0,
          status: 0,
          declare: formatTexarea(formParams.value.declare),
          currentStock: formParams.value.packNum
        }
        addGiftPackSalesApi(params)
          .then((res) => {
            emit('closeDialog')
            visible.value = false
            console.log(res)
          })
          .catch((err) => {
            console.log('catch', err)
          })
      } else {
        const params = {
          ...formParams.value,
          declare: formatTexarea(formParams.value.declare),
          currentStock: formParams.value.packNum - formParams.value.soldQuantity
        }
        editGiftPackSalesApi(params)
          .then((res) => {
            emit('closeDialog')
            visible.value = false
            console.log(res)
          })
          .catch((err) => {
            console.log('catch', err)
          })
      }
    }
  })
}
function handleSelect() {
  listRef.value.init(formParams.value.cityName)
}
const giftBagData = ref({
  couponCount: null,
  id: null,
  marketingId: null,
  packName: null,
  receiveCount: null,
  status: null,
  surplusCount: null
})
function passingValue(giftBagInfo) {
  console.log(giftBagInfo)
  formParams.value.couponPackId = giftBagInfo.id
  giftBagData.value = giftBagInfo
  maxPackNum.value = giftBagData.value.surplusCount
}
function closeDialog() {
  formRef.value.resetFields()
  formParams.value = {
    couponPackId: null,
    price: null,
    packNum: null,
    sort: null,
    declare: null,
    tagId: null,
    shopImg: null,
    currentStock: null,
    packSurplusCount: 0,
    soldQuantity: 0,
    cityName: ''
  }
  Object.keys(giftBagData.value).forEach((key) => {
    giftBagData.value[key] = null
  })
}
defineExpose({
  init
})
const emit = defineEmits(['closeDialog'])
</script>
<style lang="scss" scoped>
.confirmedBox {
  display: flex;
  justify-content: end;
}
</style>
